import logging
import md5

from pylons import request, response, session
from pylons import tmpl_context as c
from pylons.controllers.util import redirect_to, url_for
from pylons.templating import render_mako as render

from homegrownauth.lib.base import BaseController
from homegrownauth.model import meta, auth

log = logging.getLogger(__name__)

class LoginController(BaseController):
    requires_auth = True

    def index(self):
        """
        Show login form. Submits to /login/submit
        """
        return render('login.mako')

    def submit(self):
        """
        Verify username and password
        """
        # Both fields filled?
        form_username = unicode(request.params.get('username'))
        form_password = unicode(request.params.get('password'))

        # Get user data from database
        query = meta.Session.query(auth.User)
        db_user = query.filter(auth.User.username==form_username).first()
        if db_user is None: # User does not exist
            return 'Db user doesn\'t exist!'

        # Wrong password? (MD5 hashes used here)
        if db_user.password != form_password: #md5.md5(form_password).hexdigest():
            return 'Wrong password!'

        # Mark user as logged in
        session['user'] = form_username
        session.save()
        self.requires_auth = True

        # Send user back to the page he originally wanted to get to
        if session.get('path_before_login'):
            redirect_to(session['path_before_login'])
        else: # if previous target is unknown just send the user to a welcome page
            return 'logged in !'

    def logout(self):
        """
        Logout the user and display a confirmation message
        """
        if 'user' in session:
            del session['user']
            session.save()
        return 'logged out !'
